import { useEffect } from "react"
import useGetUserInfo from "./useGetUserInfo"
import { useLocation, useNavigate } from "react-router-dom"
import { isLoginOrRegister, isNoNeedUserInfo, LOGIN_PATHNAME, MANGE_INDEX_PATHNAME } from "../router"

function useNavPage(waitingUserData: boolean) {
    const { username } = useGetUserInfo()
    const { pathname } = useLocation()
    const nav = useNavigate()

    useEffect(() => {
        // 等待中就不需要判断
        if (waitingUserData) return

        // 已经登录了
        if (username) {
            // 如果当前的路由是登录页或注册页
            if (isLoginOrRegister(pathname)) {
                // 跳转到我的问卷页面
                nav(MANGE_INDEX_PATHNAME)
            }
            return
        }

        // 未登录 不需要用户信息 就直接return
        if (isNoNeedUserInfo(pathname)) {
            return
        } else {
            // 跳转到登录页
            nav(LOGIN_PATHNAME)
        }
    }, [waitingUserData, username, pathname])
}

export default useNavPage
